package com.lhfeiyu.action.front.other;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.lhfeiyu.config.Page;
import com.lhfeiyu.po.base.BaseGoods;
import com.lhfeiyu.service.AuthCheckService;
import com.lhfeiyu.service.base.BaseGoodsService;
import com.lhfeiyu.tools.base.Result;

@Controller
public class ShakeAction {
	@Autowired
	private BaseGoodsService goodsService;
	@Autowired
	private AuthCheckService authCheckService;
	private static Logger logger = Logger.getLogger("R");
	
	@RequestMapping(value="/shake", method=RequestMethod.GET)
	public ModelAndView showShake(ModelMap modelMap,HttpServletRequest request
			,@RequestParam(required=false) String r) {
		JSONObject json = new JSONObject();
		modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
		return new ModelAndView(Page.shake);
	}
	
	@ResponseBody
	@RequestMapping(value="/getGoodsForShake", method=RequestMethod.POST)
	public JSONObject getGoodsForShake(HttpServletRequest request,
			@RequestParam(required=false)Integer typeId) {
		JSONObject json = new JSONObject();
		try {
			/*User user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}//map.put("userId", user.getId());*/
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("forAuction", 1);//过滤掉正在拍卖的藏品
			map.put("random", 1);//随机查询商品：摇一摇
			if(null != typeId){
				map.put("catId", typeId);//藏品类型
			}
			Integer count = goodsService.selectCountByCondition(map);
			if(count > 0){
				Random r = new Random();
				int start = r.nextInt(count);
				map.put("start", start);
				map.put("count", 1);
				List<BaseGoods> goodsList = goodsService.selectListByCondition(map);
				if(null != goodsList && goodsList.size()>0){
					json.put("goods", goodsList.get(0));
					json.put("status", "success");
				}
			}else{
				json.put("msg", "没有找到合适的藏品");
				json.put("status", "failure");
			}
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR-getGoodsForShake-加载摇一摇商品出现异常-", json);
		}
		return Result.success(json);
	}
	
}
